from flask import Blueprint, request, redirect, url_for
from common.libs.Helper import ops_renderJSON, iPagenation, ops_render
from common.models.parter_index import ParterIndex
from common.models.parter_detail import ParterDetail
from common.models.parter_record import ParterRecord
from common.models.pickclass import Pickclass
from application import db, app
from common.libs.DataHelper import getCurrentTime
import flask_excel as excel
from qiniu import Auth
from qiniu import put_data
from qiniu import BucketManager
import os
from sqlalchemy import and_, or_

parter_page = Blueprint("parter_page", __name__)


def pagesadmin(parterindex):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': parterindex.count(),
        "page_size": 8,
        'page': page,
        'url': "/parter/parterindex?",
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    parterindex = parterindex[offset:limit]

    return pages, parterindex


def pagessearch(parterindex, url):
    req = request.values
    page = 1
    if 'p' in req and req['p']:
        page = int(req['p'])

    page_params = {
        'total_count': parterindex.count(),
        "page_size": 8,
        'page': page,
        'url': "/parter/partersearch?" + url,
    }
    pages = iPagenation(page_params)
    # -1 - 30,30 - 60 ,60 - 90
    offset = (page - 1) * page_params['page_size']
    limit = page * page_params['page_size']
    parterindex = parterindex[offset:limit]

    return pages, parterindex


@parter_page.route('/partersearch', methods=['GET', 'POST'])
def partersearch():
    # 字典接收所有参数
    paramslist = request.args.to_dict()

    sdate = request.args.get('sdate')
    edate = request.args.get('edate')
    gctype = request.args.get('gctype')
    if gctype == None:
        gctype = ""
    zytype = request.args.get('zytype')
    if zytype == None:
        zytype = ""
    name = request.args.get('name')
    isdone = request.args.get('isdone')
    area = request.args.get('area')
    datetype = request.args.get('datetype')

    # 多选数组准备
    list1 = []
    list2 = []
    list3 = []
    if gctype != "null":
        gctypelist = gctype.split(',')
        for i in gctypelist:
            list1.append("%" + i + "%")
        print(list1)
    if zytype != "null":
        zytypelist = zytype.split(',')
        for i in zytypelist:
            list2.append("%" + i + "%")
        print(list2)
    if area != "null":
        arealist = area.split(',')
        for i in arealist:
            list3.append("%" + i + "%")
        print(list3)

    # 删除时间范围和多选条件
    del paramslist['sdate']
    del paramslist['edate']
    del paramslist['gctype']
    del paramslist['zytype']
    del paramslist['area']
    del paramslist['datetype']

    # 删除未选择的条件
    for key in list(paramslist.keys()):
        if paramslist.get(key) == "不限":
            del paramslist[key]
    for key in list(paramslist.keys()):
        if not paramslist.get(key):
            del paramslist[key]
    if "p" in paramslist:
        del paramslist["p"]

    # 获取参数拼接翻页url

    url = "gctype=" + gctype + "&zytype=" + zytype + "&name=" + name + "&mark=1" + "&sdate=" + sdate + "&edate=" + edate + "&isdone=" + isdone + "&area=" + area + "&datetype=" + datetype

    parterclassa = Pickclass.query.filter_by(type="承建商", classone="A类").all()
    parterclassb = Pickclass.query.filter_by(type="承建商", classone="B类").all()

    if name != "":
        parterindex = ParterIndex.query.filter(ParterIndex.name.like('%' + name + '%'))
        pages, parterindex = pagessearch(parterindex, url)
        num=str(ParterIndex.query.filter(ParterIndex.name.like('%' + name + '%')).count())
        return ops_render("/parter/parterindex.html",
                          {"parterindex": parterindex, "pages": pages, "num": num, "parterclassa": parterclassa,
                           "parterclassb": parterclassb})
    # 如果通过日期筛选
    if sdate != "" and edate != "":
        if datetype == "考察日期":
            parterindex = ParterIndex.query.filter_by(mark=1).filter_by(**paramslist).filter(
                ParterIndex.kcdate >= sdate,
                ParterIndex.kcdate <= edate).filter(or_(*[ParterIndex.gctype.like(w) for w in list1])).filter(
                or_(*[ParterIndex.zytype.like(w) for w in list2])).filter(
                or_(*[ParterIndex.area.like(w) for w in list3])).order_by(
                ParterIndex.created_time.desc())
            pages, parterindex = pagessearch(parterindex, url)
            num = str(ParterIndex.query.filter_by(mark=1).filter_by(**paramslist).filter(ParterIndex.kcdate >= sdate,
                                                                                         ParterIndex.kcdate <= edate).filter(
                or_(*[ParterIndex.gctype.like(w) for w in list1])).filter(
                or_(*[ParterIndex.zytype.like(w) for w in list2])).filter(
                or_(*[ParterIndex.area.like(w) for w in list3])).order_by(
                ParterIndex.created_time.desc()).count())

        if datetype == "预审日期":
            parterindex = ParterIndex.query.filter_by(mark=1).filter_by(**paramslist).filter(
                ParterIndex.ysdate >= sdate,
                ParterIndex.ysdate <= edate).filter(or_(*[ParterIndex.gctype.like(w) for w in list1])).filter(
                or_(*[ParterIndex.zytype.like(w) for w in list2])).filter(
                or_(*[ParterIndex.area.like(w) for w in list3])).order_by(
                ParterIndex.created_time.desc())
            pages, parterindex = pagessearch(parterindex, url)
            num = str(ParterIndex.query.filter_by(mark=1).filter_by(**paramslist).filter(ParterIndex.ysdate >= sdate,
                                                                                         ParterIndex.ysdate <= edate).filter(
                or_(*[ParterIndex.gctype.like(w) for w in list1])).filter(
                or_(*[ParterIndex.zytype.like(w) for w in list2])).filter(
                or_(*[ParterIndex.area.like(w) for w in list3])).order_by(
                ParterIndex.created_time.desc()).count())
        return ops_render("/parter/parterindex.html",
                          {"parterindex": parterindex, "pages": pages, "num": num, "parterclassa": parterclassa,
                           "parterclassb": parterclassb})

    # 如果没有日期筛选
    else:
        parterindex = ParterIndex.query.filter_by(mark=1).filter(
            or_(*[ParterIndex.gctype.like(w) for w in list1])).filter(
            or_(*[ParterIndex.zytype.like(w) for w in list2])).filter(
            or_(*[ParterIndex.area.like(w) for w in list3])).order_by(
            ParterIndex.created_time.desc())
        pages, parterindex = pagessearch(parterindex, url)
        num = str(ParterIndex.query.filter_by(mark=1).filter(or_(*[ParterIndex.gctype.like(w) for w in list1])).filter(
            or_(*[ParterIndex.zytype.like(w) for w in list2])).filter(
            or_(*[ParterIndex.area.like(w) for w in list3])).order_by(
            ParterIndex.created_time.desc()).count())
        return ops_render("/parter/parterindex.html",
                          {"parterindex": parterindex, "pages": pages, "num": num, "parterclassa": parterclassa,
                           "parterclassb": parterclassb})


@parter_page.route('/parterindex', methods=['GET', 'POST'])
def parterindex():
    parterindex = ParterIndex.query.filter_by(mark=1).order_by(ParterIndex.created_time.desc())

    num = str(ParterIndex.query.filter_by(mark=1).count())
    parterclassa = Pickclass.query.filter_by(type="承建商", classone="A类").all()
    parterclassb = Pickclass.query.filter_by(type="承建商", classone="B类").all()
    pages, parterindex = pagesadmin(parterindex)
    return ops_render("/parter/parterindex.html",
                      {"parterindex": parterindex, "pages": pages, "num": num, "parterclassa": parterclassa,
                       "parterclassb": parterclassb})


@parter_page.route('/parterdetail', methods=['GET', 'POST'])
def parterdetail():
    id = request.args.get("id")
    parterindex = ParterIndex.query.filter_by(id=id, mark=1).first()
    one = ParterDetail.query.filter_by(pid=id, classone="资格预审", mark=1).all()
    two = ParterDetail.query.filter_by(pid=id, classone="考察评审", mark=1).all()
    # three = ParterDetail.query.filter_by(pid=id, classone="名录", mark=1).all()
    # four = ParterDetail.query.filter_by(pid=id, classone="履约", mark=1).all()

    onerecord = ParterRecord.query.filter_by(pid=id, status="资格预审", mark=1).order_by(ParterRecord.id.desc()).first()
    tworecord = ParterRecord.query.filter_by(pid=id, status="考察评审", mark=1).order_by(ParterRecord.id.desc()).first()
    # threerecord = ParterRecord.query.filter_by(pid=id, status="名录", mark=1).order_by(ParterRecord.id.desc()).first()
    # fourrecord = ParterRecord.query.filter_by(pid=id, status="履约", mark=1).order_by(ParterRecord.id.desc()).first()
    title = "承建商入库审查前存档"
    return ops_render("/parter/parterdetail.html",
                      {"one": one, "two": two, "parterindex": parterindex,
                       "onerecord": onerecord, "tworecord": tworecord, "title": title})


# 上传文件
@parter_page.route('/upload', methods=['GET', 'POST'])
def uploadfile():
    # 从前端获取文件
    f = request.files.getlist('files')
    classone = request.form.get('classone')
    # classtwo = request.form.get('classtwo')
    kctype = request.form.get('kctype')
    pid = request.form.get('pid')
    uid = request.form.get('uid')
    time = getCurrentTime()

    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'library-filestore'
    # http://+外链域名
    domian_name = 'http://libraryfilestore.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等

    for item in f:
        file = item.read()
        name = item.filename
        uploadname = pid + "-" + name
        token = q.upload_token(bucket_name, uploadname, 3600)
        ret, info = put_data(token, uploadname, data=file)
        url = domian_name + uploadname

        name, type1 = os.path.splitext(name)
        type = type1.replace(".", "")
        size = len(file) / 1000000
        size = round(size, 2)

        parterdetail = ParterDetail()
        parterdetail.type = type
        parterdetail.size = size
        parterdetail.url = url
        parterdetail.mark = 1
        parterdetail.uid = uid
        parterdetail.pid = pid
        parterdetail.classone = classone
        parterdetail.classtwo = name
        parterdetail.created_time = parterdetail.updated_time = time
        db.session.add(parterdetail)
        db.session.commit()

        # 更新承建商首页信息
        if classone == "考察评审":
            parterindex = ParterIndex.query.filter_by(id=pid).first()
            parterindex.status = classone
            parterindex.isdone = "是"
            db.session.commit()
        else:
            parterindex = ParterIndex.query.filter_by(id=pid).first()
            parterindex.status = classone
            db.session.commit()

        # 更新记录信息
        parterrecord = ParterRecord()
        parterrecord.status = classone
        parterrecord.classtwo = name
        parterrecord.pid = pid
        parterrecord.mark = 1
        parterrecord.type = kctype
        parterrecord.result = "通过"
        parterrecord.created_time = parterrecord.updated_time = getCurrentTime()
        db.session.add(parterrecord)
        db.session.commit()

    return ops_renderJSON(msg="操作成功")


@parter_page.route('/denyrecord', methods=['GET', 'POST'])
def denyrecord():
    req = request.values
    pid = req['pid'] if "pid" in req else ""
    classone = req['classone'] if "classone" in req else ""
    reason = req['reason'] if "reason" in req else ""

    parterrecord = ParterRecord()
    parterrecord.status = classone
    parterrecord.reason = reason
    parterrecord.result = "不通过"
    parterrecord.pid = pid
    parterrecord.mark = 1
    parterrecord.created_time = parterrecord.updated_time = getCurrentTime()
    db.session.add(parterrecord)
    db.session.commit()

    parterindex = ParterIndex.query.filter_by(id=pid).first()
    parterindex.isdone = "是"
    db.session.commit()

    return ops_renderJSON(msg="更改成功")


@parter_page.route('/detaildelete', methods=['GET', 'POST'])
def deletedetail():
    id = request.args.get('id')
    parterdetail = ParterDetail.query.filter_by(id=id).first()
    classone = str(parterdetail.classone)
    classtwo = str(parterdetail.classtwo)
    # time = str(parterdetail.updated_time)
    type = str(parterdetail.type)
    pid = str(parterdetail.pid)
    pid1 = int(pid)

    uploadname = pid + "-" + classtwo + "." + type
    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 初始化Auth状态
    q = Auth(access_key, secret_key)
    # 初始化BucketManager
    bucket = BucketManager(q)
    # 你要测试的空间， 并且这个key在你空间中存在
    bucket_name = 'library-filestore'
    # 删除bucket_name 中的文件 key
    ret, info = bucket.delete(bucket_name, uploadname)
    if info.status_code == 200:
        parterrecord = ParterRecord.query.filter_by(pid=pid, mark=1, classtwo=classtwo, status=classone,
                                                    result='通过').first()
        parterrecord.mark = 0
        db.session.commit()

        parterdetail1 = ParterDetail.query.filter_by(id=id).first()
        parterdetail1.mark = 0
        db.session.commit()

        return ops_renderJSON(msg="删除成功", data={"pid": pid})
    if info.status_code == 612:
        parterrecord = ParterRecord.query.filter_by(pid=pid, mark=1, classtwo=classtwo, status=classone,
                                                    result='通过').first()
        parterrecord.mark = 0
        db.session.commit()

        parterdetail1 = ParterDetail.query.filter_by(id=id).first()
        parterdetail1.mark = 0
        db.session.commit()

        return ops_renderJSON(msg="该文件已删除", data={"pid": pid})
    else:
        return ops_renderJSON(msg="删除失败")


# 新增台账
@parter_page.route('/addindex', methods=['GET', 'POST'])
def addindex():
    req = request.values
    name = req['name'] if "name" in req else ""
    type = req['type'] if "type" in req else ""
    address = req['address'] if "address" in req else ""
    linker = req['linker'] if "linker" in req else ""
    phone = req['phone'] if "phone" in req else ""
    owner = req['owner'] if "owner" in req else ""
    gctype = req['gctype'] if "gctype" in req else ""
    zytype = req['zytype'] if "zytype" in req else ""
    uid = req['uid'] if "uid" in req else ""
    offer = req['offer'] if "offer" in req else ""
    area = req['area'] if "area" in req else ""

    index = ParterIndex()
    index.name = name
    index.type = type
    index.address = address
    index.linker = linker
    index.mark = 1
    index.uid = uid
    index.phone = phone
    index.owner = owner
    index.gctype = gctype
    index.zytype = zytype
    index.status = "资格预审"
    index.isdone = "否"
    index.offer = offer
    index.area = area
    index.created_time = index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()

    return ops_renderJSON(msg="新建成功")


# 修改台账信息
@parter_page.route('/updataindex', methods=['GET', 'POST'])
def updataindex():
    req = request.values
    id = req['id'] if "id" in req else ""
    name = req['name'] if "name" in req else ""
    type = req['type'] if "type" in req else ""
    address = req['address'] if "address" in req else ""
    linker = req['linker'] if "linker" in req else ""
    phone = req['phone'] if "phone" in req else ""
    owner = req['owner'] if "owner" in req else ""
    gctype = req['gctype'] if "gctype" in req else ""
    zytype = req['zytype'] if "zytype" in req else ""
    uid = req['uid'] if "uid" in req else ""
    offer = req['offer'] if "offer" in req else ""
    area = req['area'] if "area" in req else ""

    index = ParterIndex.query.filter_by(id=id).first()
    index.name = name
    index.type = type
    index.address = address
    index.linker = linker
    index.mark = 1
    index.uid = uid
    index.phone = phone
    index.owner = owner
    index.gctype = gctype
    index.zytype = zytype
    index.offer = offer
    index.area = area
    index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()
    return ops_renderJSON(msg="更新成功")


@parter_page.route('/deleteindex', methods=['GET', 'POST'])
def deleteindex():
    id = request.args.get("id")
    index = ParterIndex.query.filter_by(id=id).first()
    index.mark = 0
    index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()
    return ops_renderJSON(msg="删除成功")


@parter_page.route('/updatedate', methods=['GET', 'POST'])
def updatedate():
    id = request.args.get("pid")
    ysdate = request.args.get("ysdate")
    if not ysdate:
        ysdate = "0000-00-00"
    kcdate = request.args.get("kcdate")
    if not kcdate:
        kcdate = "0000-00-00"
    index = ParterIndex.query.filter_by(id=id).first()
    index.ysdate = ysdate
    index.kcdate = kcdate
    index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()
    return redirect(url_for('parter_page.parterdetail', id=id))
